import { defineStore } from 'pinia'
import api from '../api'

export const useObjectivesStore = defineStore('objectives', {
  state: () => ({
    objectives: [],
    keyResults: [],
    loading: false,
    error: null
  }),
  getters: {
    getObjectiveById: (state) => (id) => {
      return state.objectives.find(obj => obj.id === id)
    },
    getKeyResultsByObjectiveId: (state) => (objectiveId) => {
      return state.keyResults.filter(kr => kr.objective === objectiveId)
    }
  },
  actions: {
    // 创建关键结果
    async createKeyResult(keyResultData) {
      this.loading = true;
      this.error = null;
      try {
        const apiData = {
          title: keyResultData.title,
          description: keyResultData.description,
          objective: keyResultData.objective,
          progress: keyResultData.progress || 0,
          status: 'not_started'
        };
        
        const response = await api.post('/key-results/', apiData);
        
        this.keyResults.push(response.data);
        this.loading = false;
        return response.data;
      } catch (error) {
        console.error('Error creating key result:', error);
        this.error = error.message || 'Failed to create key result';
        this.loading = false;
        throw error;
      }
    },
    
    async fetchObjectives() {
      this.loading = true
      this.error = null
      try {
        const response = await api.get('/objectives/')
        this.objectives = response.data
        this.loading = false
      } catch (error) {
        console.error('Error fetching objectives:', error)
        this.error = error.message || 'Failed to fetch objectives'
        this.loading = false
      }
    },
    
    async fetchKeyResults(objectiveId = null) {
      this.loading = true
      this.error = null
      try {
        let url = '/key-results/'
        if (objectiveId) {
          url += `?objective=${objectiveId}`
        }
        
        const response = await api.get(url)
        this.keyResults = response.data
        this.loading = false
      } catch (error) {
        console.error('Error fetching key results:', error)
        this.error = error.message || 'Failed to fetch key results'
        this.loading = false
      }
    },
    
    async createObjective(objectiveData) {
      this.loading = true
      this.error = null
      try {
        // 转换前端字段到后端字段
        const apiData = {
          title: objectiveData.title,
          description: objectiveData.description,
          // 将前端的due_date映射到后端的end_date，并确保日期格式正确
          end_date: objectiveData.end_date, // 已经是YYYY-MM-DD格式
          start_date: objectiveData.start_date || new Date().toISOString().split('T')[0],
          status: objectiveData.status || 'not_started',
          progress: objectiveData.progress || 0,
          parent: objectiveData.parent,
          level: objectiveData.level || 'personal'
        }
        
        const response = await api.post('/objectives/', apiData)
        this.objectives.push(response.data)
        this.loading = false
        return response.data
      } catch (error) {
        console.error('Error creating objective:', error)
        this.error = error.message || 'Failed to create objective'
        this.loading = false
        throw error
      }
    },

    async updateObjective(id, objectiveData) {
      this.loading = true
      this.error = null
      try {
        if (!id) {
          throw new Error('目标ID不能为空')
        }

        // 转换前端字段到后端字段
        const apiData = {
          title: objectiveData.title,
          description: objectiveData.description,
          end_date: objectiveData.end_date || objectiveData.due_date,
          start_date: objectiveData.start_date || new Date().toISOString().split('T')[0],
          status: objectiveData.status || 'not_started',
          progress: objectiveData.progress || 0,
          parent: objectiveData.parent,
          level: objectiveData.level || 'personal'
        }
        
        const response = await api.put(`/objectives/${id}/`, apiData)
        
        // 更新本地数据
        const index = this.objectives.findIndex(obj => obj.id === id)
        if (index !== -1) {
          this.objectives[index] = response.data
        }
        
        this.loading = false
        return response.data
      } catch (error) {
        console.error('Error updating objective:', error)
        this.error = error.message || 'Failed to update objective'
        this.loading = false
        throw error
      }
    },
    
    
    async deleteObjective(id) {
      this.loading = true
      this.error = null
      try {
        await api.delete(`/objectives/${id}/`)
        
        this.objectives = this.objectives.filter(obj => obj.id !== id)
        this.loading = false
        return true
      } catch (error) {
        console.error('Error deleting objective:', error)
        this.error = error.message || 'Failed to delete objective'
        this.loading = false
        throw error
      }
    }
  }
})